<template>
  <div>
    <h3>阶段训练计划表</h3>
    <div class="body">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row style="margin-bottom: 20px;" type="flex">
            <el-col :span="15">
              <sportChangesportItem ref="sport2sportItem" search="search" :sportChangesportItemData="sportChangesportItemData"
                @selectDataChange='searchSelectDataChange' title="撰写者" />
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col :span="6">
              <el-input v-model="searchForm.name" size="small" style="width: 70%;" suffix-icon="el-icon-view" placeholder="输入文档标题"></el-input>
            </el-col>
            <el-col :span="8">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="center" unlink-panels style="width: 70%;"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="5">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" border max-height="800" stripe highlight-hover-row highlight-current-row resizable
        :loading="loading" :data="dataList" @sort-change="sortChange" :export-config="{}">
        <vxe-column field="checkbox" type="checkbox" width="60"></vxe-column>
        <vxe-table-column field="name" title="文档标题" sortable></vxe-table-column>
        <vxe-table-column field="available" title="文档类型" sortable></vxe-table-column>
        <vxe-table-column field="sport" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column field="sportItem" title="运动小项" sortable></vxe-table-column>
        <vxe-table-column field="emp" title="撰写者" sortable></vxe-table-column>
        <vxe-table-column field="signersName" title="署名" sortable></vxe-table-column>
        <vxe-table-column field="createDate" title="创建日期" sortable></vxe-table-column>
        <vxe-table-column field="beginDate" title="开始日期" sortable></vxe-table-column>
        <vxe-table-column field="endDate" title="截止日期" sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="180">
          <template #default="{ row }">
            <el-button @click="printModalShow(row)" type="primary" circle size="medium" icon="el-icon-view"></el-button>
            <el-button @click="planEdit(row)" type="primary" circle size="medium" icon="el-icon-edit"></el-button>
            <el-button @click="planDelete(row)" type="primary" circle size="medium" icon="el-icon-delete"></el-button>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
  </div>
</template>

<script>
  import {doc_excel_all,allType,doc_excel_delete,doc_excel_select,batchPrint} from '@/api/plan.js'
  import {currentRoleEmployee} from '@/api/person.js'
  import {sport_by_org,sport_item} from '@/api/dict.js'
  import sportChangesportItem from '@/components/sport2sportItem/sport2sportItem.vue'
  export default {
    components: {
      sportChangesportItem,
    },
    props: ['docClassId'],
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },{
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_emp: {},
        dict_sport: {},
        dict_sportItem: {},
        printModal: false,
        previewData: {},
        currentDocClassId: null,
        searchForm: {
          name: null,
          empId: null,
          sportId: null,
          sportItemId: null,
          beginDate: null,
          endDate: null,
        },
        doubleDate: null,
        sportChangesportItemData: {},
        printWordModal: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getPlanList()
      })
    },
    methods: {
      searchSubmit() {
        let data = {}
        if(this.searchForm.empId) data.empId = this.searchForm.empId
        if(this.searchForm.name) data.name = this.searchForm.name
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if (this.doubleDate){
          data.beginDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        doc_excel_select(data).then(res=>{
          if(res.code === 200 && res.data.length != 0) {
            this.init_data(res.data.reverse())
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      clearTableFilter() {
        this.searchForm = {
          name: null,
          empId: null,
          sportId: null,
          sportItemId: null,
          beginDate: null,
          endDate: null,
        }
        this.doubleDate = null
        this.sportChangesportItemData = {}
        this.getPlanList()
      },
      searchSelectDataChange({
        sportId,
        sportItemId,
        person
      }) {
        this.searchForm.sportId = sportId
        this.searchForm.empId = person
        this.searchForm.sportItemId = sportItemId
      },
      planDelete(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          doc_excel_delete({docExcelId:row.docExcelId}).then(res=>{
            if(res.code === 200) {
              this.$message.success('删除成功！')
              this.getPlanList()
            }else{
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      planEdit(row) {
        const { href } = this.$router.resolve({
            path: '/trainPlan/viewTrainPlanExcelMk',
            query: {docExcelId:row.docExcelId}
        });
        window.open(href, '_blank');
      },
      printModalShow(row) {
        const { href } = this.$router.resolve({
            path: '/trainPlan/viewTrainPlanExcelMk',
            query: {docExcelId:row.docExcelId,isPreview:true}
        });
        window.open(href, '_blank');
      },
      getPlanList() {
        doc_excel_all(this.docClassId).then(res=>{
         if(res.code === 200 && res.data.length!=0) {
            this.init_data(res.data)
         }else{
           this.defaultDataList = []
         }
       }).then(()=>{
         this.findList()
       })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item=>{
          item.emp = this.dict_emp[item.empId]
          item.available = '阶段训练计划表'
          item.sport = this.dict_sport[item.sportId]
          item.spoetItem = this.dict_sportItem[item.sportItemId]
          item.createDate = this.$moment(item.createDate).format('YYYY-MM-DD')=='Invalid date'?'':this.$moment(item.createDate).format('YYYY-MM-DD')
          item.beginDate = this.$moment(item.beginDate).format('YYYY-MM-DD')=='Invalid date'?'':this.$moment(item.beginDate).format('YYYY-MM-DD')
          item.endDate = this.$moment(item.endDate).format('YYYY-MM-DD')=='Invalid date'?'':this.$moment(item.endDate).format('YYYY-MM-DD')
          item.status = item.statusId == 1 ? "正式" : "草稿"
          if(item.signers){
            let arr = item.signers.split(',')
            let signersArr = []
            arr.forEach(signers=>{
              signersArr.push(this.dict_emp[signers])
            })
            item.signersName = signersArr.join(',')
          }
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          currentRoleEmployee().then(res=>{
            res.data.forEach(item=>{
              this.dict_emp[item.empId] = item.name
            })
            sport_by_org().then(res=>{
              this.dict_sport = res
            })
            sport_item().then(res=>{
              this.dict_sportItem = res
              resolve()
            })
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        this.page.currentPage = 1
        this.page.pageSize = this.defaultDataList.length
        this.findList()
      },
      findList() {
        this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultDataList.length
          this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .body{
    padding: 10px;
    background-color: #FFFFFF;
  }
</style>
